import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { ConversationItem } from '@/types/app'

export const useConversationStore = defineStore('conversation', () => {
  // 状态
  const conversationList = ref<ConversationItem[]>([])
  const currConversationId = ref<string>('')
  const currInputs = ref<Record<string, any>>({})

  // 计算属性
  const isNewConversation = computed(
    () => currConversationId.value === '' || currConversationId.value === '-1'
  )

  const currConversationInfo = computed(() => {
    return conversationList.value.find((item) => item.id === currConversationId.value)
  })

  // 方法
  const setConversationList = (list: ConversationItem[]) => {
    conversationList.value = list
  }

  const setCurrConversationId = (id: string, _appId?: string) => {
    currConversationId.value = id
    // 保存到本地存储
    if (typeof window !== 'undefined') {
      localStorage.setItem('currentConversationId', id)
    }
  }

  const setCurrInputs = (inputs: Record<string, any>) => {
    currInputs.value = inputs
  }

  const createNewChat = () => {
    currConversationId.value = '-1'
    currInputs.value = {}
  }

  const getConversationIdFromStorage = (): string | null => {
    if (typeof window !== 'undefined') {
      return localStorage.getItem('currentConversationId')
    }
    return null
  }

  const addConversation = (conversation: ConversationItem) => {
    conversationList.value.unshift(conversation)
  }

  const updateConversation = (id: string, updates: Partial<ConversationItem>) => {
    const index = conversationList.value.findIndex((item) => item.id === id)
    if (index !== -1) {
      conversationList.value[index] = { ...conversationList.value[index], ...updates }
    }
  }

  const removeConversation = (id: string) => {
    const index = conversationList.value.findIndex((item) => item.id === id)
    if (index !== -1) {
      conversationList.value.splice(index, 1)
    }
  }

  return {
    // 状态
    conversationList,
    currConversationId,
    currInputs,

    // 计算属性
    isNewConversation,
    currConversationInfo,

    // 方法
    setConversationList,
    setCurrConversationId,
    setCurrInputs,
    createNewChat,
    getConversationIdFromStorage,
    addConversation,
    updateConversation,
    removeConversation
  }
})
